<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-8-10
 * Time: 下午5:46
 */

namespace common\models\db;
use common\members\wodrow\tools\Model;
use common\rewrite\deepziyu\yii_fast_api\ApiException;


/**
 * Class Equipment
 * @package common\models\db
 *
 * @property EquipmentOperateLog[] $equipmentLoginLogs
 * @property EquipmentUser[] $equipmentUsers
 * @property User[] $users
 */
class Equipment extends \common\models\db\tables\Equipment
{
    /**
     * @param $uuid
     * @param string $app_version_id 安装的app版本ID
     * @throws ApiException
     * @return static
     */
    public static function generateEquipment($uuid, $app_version_id)
    {
        $equipment = self::findOne(['uuid' => $uuid]);
        if (!$equipment){
            $equipment = new self();
            $equipment->uuid = $uuid;
            $equipment_app_version = EquipmentAppVersion::findOne(['app_version_id' => $app_version_id]);
            $equipment->app_version_id = $equipment_app_version->id;
        }
        $equipment->last_app_use_at = Yii_BT_TIME;
        if (!$equipment->save()){
            throw new ApiException(201808142011, '设备信息更新失败:'.Model::getModelError($equipment));
        }
        return $equipment;
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEquipmentLoginLogs()
    {
        return $this->hasMany(EquipmentOperateLog::className(), ['equipment_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEquipmentUsers()
    {
        return $this->hasMany(EquipmentUser::className(), ['equipment_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUsers()
    {
        return $this->hasMany(User::className(), ['id' => 'user_id'])->viaTable('{{%equipment_user}}', ['equipment_id' => 'id']);
    }
}